#pragma once

#include <iostream>
#include <string>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <unistd.h>
#include <sys/wait.h>
#include <functional>
#include "Task.hpp"
#include "Thread.hpp"
#include "ThreadPool.hpp"

#include "err.hpp"

namespace Alpaca
{
    static const uint16_t defaultport = 8080;
    static const int backlog = 32;
    using func_t = std::function<std::string(const std::string &)>;

    class TcpServer;
    class ThreadData
    {
    public:
        ThreadData(int fd, const std::string &ip, uint16_t port, TcpServer *ts)
            : socket(fd), clientip(ip), clientport(port), current(ts)
        {
        }

    public:
        int socket;
        std::string clientip;
        uint16_t clientport;
        TcpServer *current;
    };

    class TcpServer
    {
    public:
        TcpServer(func_t func, uint16_t port = defaultport) : _func(func), _port(port), _quit(true)
        {
        }
        ~TcpServer()
        {
        }
        void initserver()
        {
            _listensock = socket(AF_INET, SOCK_STREAM, 0);
            if (_listensock < 0)
            {
                std::cerr << "create socket error" << std::endl;
                exit(SOCKET_ERR);
            }

            struct sockaddr_in local;
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_port = htons(_port);

            if (bind(_listensock, (sockaddr *)&local, sizeof(local)) != 0)
            {
                std::cerr << "bind socket error" << std::endl;
                exit(BIND_ERR);
            }

            if (listen(_listensock, backlog) != 0)
            {
                std::cerr << "listen socket error" << std::endl;
                exit(LISTEN_ERR);
            }
        }
        void start()
        {
            _quit = false;
            while (!_quit)
            {
                struct sockaddr_in client;
                socklen_t len = sizeof(client);
                int sock = accept(_listensock, (sockaddr *)&client, &len);
                if (sock < 0)
                {
                    std::cerr << "accept socket error" << std::endl;
                    continue;
                }

                std::string clientip = inet_ntoa(client.sin_addr);
                uint16_t port = ntohs(client.sin_port);
                std::string name = clientip;
                name += "-";
                name += std::to_string(port);

                std::cout << "获取新连接成功 " << sock << " from " << _listensock << "," << name << std::endl;

                // 串行
                // service(sock);

                // 多进程
                // int id = fork();
                // if (id < 0)
                // {
                //     close(sock);
                //     continue;
                // }
                // else if (id == 0) // 子进程
                // {
                //     close(_listensock);
                //     if(fork() > 0) exit(0);
                //     service(sock);
                //     exit(0);
                // }

                // close(sock);
                // pid_t ret = waitpid(id, nullptr, 0);
                // if (ret == id)
                //     std::cout << "wait child " << id << "success" << std::endl;

                // 多进程
                // pthread_t tid;
                // ThreadData *td = new ThreadData(sock, clientip, clientport, this);
                // pthread_create(&tid, nullptr, threadRoutine, &td);

                // 线程池
                // 可以将输出的操作交给线程处理
                Task t(sock, clientip, port, std::bind(&TcpServer::service, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
                ThreadPool<Task>::getinstance()->pushtask(t);
            }
        }

        static void *threadRoutine(void *args)
        {
            pthread_detach(pthread_self());
            ThreadData *td = static_cast<ThreadData *>(args);
            td->current->service(td->socket, td->clientip, td->clientport);
            delete td;
            return nullptr;
        }

        void service(int sock, const std::string &ip, const uint16_t &port)
        {
            char buffer[1024];
            std::string name = ip + '-' + std::to_string(port);
            while (true)
            {
                ssize_t s = read(sock, buffer, sizeof(buffer) - 1);
                if (s > 0)
                {
                    buffer[s] = '\0';

                    std::string res = _func(buffer);

                    std::cout << name << "# " << res << std::endl;

                    write(sock, buffer, sizeof(buffer) - 1);
                }
                else if (s == 0)
                {
                    close(sock);
                    std::cout << ip << " quit" << std::endl;
                    break;
                }
                else
                {
                    close(sock);
                    std::cout << "recv error" << std::endl;
                    break;
                }
            }
        }

    private:
        uint16_t _port;
        int _listensock;
        bool _quit;
        func_t _func;
    };
}